'use server';

import { getSession } from '@/lib/auth';
import { db } from '@/lib/db';
import { address } from '@/lib/db/schema/common';
import { result, withZod } from '@/lib/utils';
import { eq } from 'drizzle-orm';
import { revalidatePath } from 'next/cache';
import { z } from 'zod';
import { BizError, ErrorCode } from '../error';
import { addressSchema } from './schema/address';

export const createAddress = withZod(addressSchema, async (data) => {
  try {
    const session = await getSession();
    if (!session) throw new BizError(ErrorCode.Unauthorized, '用户未登录');
    if (!data.address) throw new BizError(ErrorCode.NotFound, '地址不存在');
    await db.insert(address).values({
      name: data.name,
      phone: data.phone,
      userId: session.user.id,
      poiId: data.address.id,
      address: data.address.address,
      longitude: data.address.longitude,
      latitude: data.address.latitude,
    });
    revalidatePath('/');
    return result();
  } catch (error) {
    return result(error, '创建地址失败,请重试');
  }
});

export const updateAddress = withZod(
  addressSchema.extend({ id: z.number() }),
  async (data) => {
    try {
      const session = await getSession();
      if (!session) throw new BizError(ErrorCode.Unauthorized, '用户未登录');
      if (!data.address) throw new BizError(ErrorCode.NotFound, '地址不存在');
      await db
        .update(address)
        .set({
          name: data.name,
          phone: data.phone,
          address: data.address.address,
          poiId: data.address.id,
          longitude: data.address.longitude,
          latitude: data.address.latitude,
        })
        .where(eq(address.id, data.id));
      revalidatePath('/');
      return result();
    } catch (error) {
      return result(error, '更新地址失败,请重试');
    }
  },
);
